const app = getApp();
Page({
  data: {
    info:{
      name: '',
      phone: '',
      region: '',
      province: '',
      city: '',
      area: '',
      detail: '',
      is_default: 0,
    },
  },
 
  onLoad: function (options) {
    let that = this;
    let address_id = options.id || ''; 
    app.request('address/detail', { address_id },'GET',false,function(res){
      that.setData({
        pageShow: true,
        options: options,
        info: res.data.data || {},
      })
    })
  },
  getInput(e){
    let that = this;
    let type = e.currentTarget.dataset.type;
    let info = that.data.info;
    info[type] = e.detail.value;
    that.setData({
      info: info,
    })
  },
  //选择默认
  chooseDefault: function () {
    let that = this;
    let info = that.data.info;
    info.is_default = info.is_default==0?1:0;
    that.setData({
      info: info,
    })
  },
  bindRegionChange: function (e) {
    let that = this;
    let info = that.data.info;
    info['province'] = e.detail.value[0];
    info['city'] = e.detail.value[1];
    info['area'] = e.detail.value[2];
    that.setData({
      info: info,
    })
  },
  //保存
  sure: function (e) {
    let that = this;
    app.getFormid(e);
    let info = that.data.info;
    let name = info.name;
    let phone = info.phone;
    let province = info.province;
    let city = info.city;
    let area = info.area;
    let detail = info.detail;
    let is_default = info.is_default;
    let id = that.options.id || '';
    let reg1 = new RegExp(/^[\u4E00-\u9FA5]{2,4}$/);
    let reg2 = new RegExp(/^1(3|4|5|6|7|8|9)\d{9}$/);
    if (!name) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none',
        duration: 1500,
      })
    } else if (!reg1.exec(name)) {
      wx.showToast({
        title: "姓名格式错误",
        icon: 'none',
        duration: 1500,
      })
    } else if (!phone) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none',
        duration: 1500,
      })
    } else if (!reg2.exec(phone)) {
      wx.showToast({
        title: "手机号格式错误",
        icon: 'none',
        duration: 1500,
      })
    } else if (!province) {
      wx.showToast({
        title: '请选择所在区域',
        icon: 'none',
        duration: 1500,
      })
    } else if (!detail) {
      wx.showToast({
        title: '请输入详细地址',
        icon: 'none',
        duration: 1500,
      })
    } else {
      app.request('address/addAddress',{
        name, phone, province, city, area, detail, is_default, id
      },'GET',false,function(res){
        wx.showToast({
          title: '保存成功',
        })
        setTimeout(function () {
          wx.navigateBack({
            delta: 1,
          })
        }, 2000);
      })
    }
  },
  
})